package com.taotao.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.taotao.common.pojo.EasyUIDataGridResult;
import com.taotao.common.pojo.TaotaoResult;
import com.taotao.mapper.TbItemCatMapper;
import com.taotao.mapper.TbItemParamMapper;
import com.taotao.pojo.TbItemCat;
import com.taotao.pojo.TbItemParam;
import com.taotao.pojo.TbItemParamExample;
import com.taotao.pojo.TbItemParamExample.Criteria;
import com.taotao.service.ItemParamService;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ItemParamServiceImpl implements ItemParamService {
	@Autowired
	private TbItemParamMapper tbItemParamMapper;
	@Autowired
	private TbItemCatMapper tbItemCatMapper;

	public TaotaoResult getItemParamByCid(long cid) {
		TbItemParamExample example = new TbItemParamExample();
		Criteria criteria = example.createCriteria();
		criteria.andItemCatIdEqualTo(cid);
		List<TbItemParam> list = tbItemParamMapper
				.selectByExampleWithBLOBs(example);
		if ((list.size() > 0) && (list != null)) {
			TbItemParam tbItemParam = (TbItemParam) list.get(0);
			return TaotaoResult.ok(tbItemParam);
		}
		return TaotaoResult.ok();
	}

	public TaotaoResult insertItemParam(long cid, String paramData) {
		Date date = new Date();

		TbItemParam tbItemParam = new TbItemParam();
		tbItemParam.setItemCatId(cid);
		tbItemParam.setParamData(paramData);
		tbItemParam.setCreated(date);
		tbItemParam.setUpdated(date);

		tbItemParamMapper.insert(tbItemParam);

		return TaotaoResult.ok();
	}

	public EasyUIDataGridResult getItemList(int page, int rows) {
		PageHelper.startPage(page, rows);

		TbItemParamExample example = new TbItemParamExample();
		List<TbItemParam> list = tbItemParamMapper
				.selectByExampleWithBLOBs(example);
		for (TbItemParam tbItemParam : list) {
			long id = tbItemParam.getItemCatId();
			TbItemCat tbItemCat = tbItemCatMapper.selectByPrimaryKey(id);
			String itemCatName = tbItemCat.getName();
			tbItemParam.setItemCatName(itemCatName);
		}
		PageInfo<TbItemParam> tbItemParams = new PageInfo<TbItemParam>(list);

		EasyUIDataGridResult result = new EasyUIDataGridResult();
		result.setTotal(tbItemParams.getTotal());
		result.setRows(tbItemParams.getList());

		return result;
	}

	public TaotaoResult deleteItemParam(long[] ids) {
		for (long l : ids) {
			tbItemParamMapper.deleteByPrimaryKey(l);
		}
		return TaotaoResult.ok();
	}
}
